package com.zzy.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzy.utils.constant.WareConstant;
import com.zzy.utils.exception.RRException;
import com.zzy.utils.utils.PageUtils;
import com.zzy.utils.utils.Query;
import com.zzy.ware.entity.PurchaseDetailEntity;
import com.zzy.ware.entity.PurchaseEntity;
import com.zzy.ware.mapper.PurchaseMapper;
import com.zzy.ware.service.PurchaseDetailService;
import com.zzy.ware.service.PurchaseService;
import com.zzy.ware.service.WareSkuService;
import com.zzy.ware.vo.MergeVo;
import com.zzy.ware.vo.PurchaseDoneVo;
import com.zzy.ware.vo.PurchaseItemDoneVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.zzy.utils.constant.WareConstant.PurchaseStatusEnum.*;


/**
 * @author KAZU
 */
@Slf4j
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, PurchaseEntity> implements PurchaseService {

	@Autowired
	private PurchaseDetailService detailService;
	
	@Autowired
	private WareSkuService wareSkuService;
	
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }
	
	@Override
	public PageUtils queryPageUnreceive(Map<String, Object> params) {
		
		IPage<PurchaseEntity> page = this.page(
				new Query<PurchaseEntity>().getPage(params),
				new QueryWrapper<PurchaseEntity>()
						.eq("status", 0)
						.or().eq("status", 1)
		);
		return new PageUtils(page);
	}
	
	@Transactional
	@Override
	public void mergePurchase(MergeVo mergeVo) {
		Long purchaseId = mergeVo.getPurchaseId();
		if (purchaseId == null) {
			/*新建一个*/
			PurchaseEntity purchaseEntity = new PurchaseEntity();
			purchaseEntity.setCreateTime(new Date());
			purchaseEntity.setUpdateTime(new Date());
			purchaseEntity.setStatus(CREATED.getCode());
			this.save(purchaseEntity);
			purchaseId = purchaseEntity.getId();
		}
		/*TODO:确认采购单状态是0或者1*/
		log.info("提交信息: {}", mergeVo.toString());
		List<Long> mergeVoItems = mergeVo.getItems();
		mergeVoItems.forEach(item -> {
			PurchaseDetailEntity entity = detailService.getOne(new QueryWrapper<PurchaseDetailEntity>()
					.eq("id", item));
			if (entity.getStatus() != CREATED.getCode() && entity.getStatus() != ASSIGNED.getCode()) {
				throw new RRException("无法合并采购项", 400);
			}
		});
		
		List<Long> items = mergeVo.getItems();
		Long finalPurchaseId = purchaseId;
		List<PurchaseDetailEntity> collect = items.stream().map(i -> {
			PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
			detailEntity.setId(i);
			detailEntity.setPurchaseId(finalPurchaseId);
			detailEntity.setStatus(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
			return detailEntity;
		}).collect(Collectors.toList());
		
		detailService.updateBatchById(collect);
		
		PurchaseEntity purchaseEntity = new PurchaseEntity();
		purchaseEntity.setId(purchaseId);
		purchaseEntity.setUpdateTime(new Date());
		this.updateById(purchaseEntity);
	}
	
	/**
	 *
	 * @param ids 采购单id
	 */
	@Override
	public void received(List<Long> ids) {
		/*1、确认但其概念采购单是新建或者已分配的状态*/
		List<PurchaseEntity> collect = ids.stream().map(id -> {
			PurchaseEntity byId = this.getById(id);
			return byId;
		}).filter(item -> {
			if (item.getStatus() == CREATED.getCode() || item.getStatus() == ASSIGNED.getCode()) {
				return true;
			} else {
				return false;
			}
		}).map(item -> {
			item.setStatus(RECEIVE.getCode());
			item.setUpdateTime(new Date());
			return item;
		}).collect(Collectors.toList());
		
		/*2、改变采购单的状态*/
		this.updateBatchById(collect);
		
		/*3、改变采购项的状态*/
		collect.forEach((item) -> {
			List<PurchaseDetailEntity> entities = detailService.listDetailByPurchaseId(item.getId());
			List<PurchaseDetailEntity> detailEntities = entities.stream().map(entity -> {
				PurchaseDetailEntity entity1 = new PurchaseDetailEntity();
				entity1.setId(entity.getId());
				entity1.setStatus(BUYING.getCode());
				return entity1;
			}).collect(Collectors.toList());
			detailService.updateBatchById(detailEntities);
		});
		
		
		
	}
	
	@Transactional
	@Override
	public void done(PurchaseDoneVo doneVo) {
		/*1、改变采购单状态*/
		Long id = doneVo.getId();
		
		/*2、改变采购项状态*/
		List<PurchaseItemDoneVo> items = doneVo.getItems();
		List<PurchaseDetailEntity> updates = new ArrayList<>();
		Boolean flag = true;
		for (PurchaseItemDoneVo item : items) {
			PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
			if (item.getStatus() == HASERROR.getCode()) {
				flag = false;
				detailEntity.setStatus(item.getStatus());
			} else {
				detailEntity.setStatus(FINISH.getCode());
				/*3、将成功的采购进行入库*/
				PurchaseDetailEntity entity = detailService.getById(item.getItemId());
				wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
				
			}
			detailEntity.setId(item.getItemId());
			updates.add(detailEntity);
		}
		detailService.updateBatchById(updates);
		
		/*改变采购单状态*/
		PurchaseEntity purchaseEntity = new PurchaseEntity();
		purchaseEntity.setId(id);
		purchaseEntity.setStatus(flag?FINISH.getCode():HASERROR.getCode());
		purchaseEntity.setUpdateTime(new Date());
		this.updateById(purchaseEntity);
		
		
	}
	
}











